<template>
  <div>
    <el-menu
      :default-active="activeIndex"
      class="el-menu-vertical-demo"
      :collapse="collapsed"
      @select="handleSelect"
    >
      <!-- 当前组织显示区域 -->
      <div class="community" v-if="community">
        <div>
          <img :src="config.getUrl(community.logo_url)" alt="Logo" class="logo" />
        </div>
        <div class="name">{{ community.community_name }}</div>
      </div>
      <template v-for="item in menuItems" :key="item.index">
        <el-sub-menu v-if="item.children" :index="item.index"  :title="item.title">
          <template #title>
            <el-icon><component :is="item.icon" /></el-icon>
            <span>{{ $t(item.title) }}</span>
          </template>
          <el-menu-item-group v-for="group in item.children" :key="group.index" :title="group.title">
            <el-menu-item v-for="subItem in group.children || [group]" :key="subItem.index" :index="subItem.index" :disabled="subItem.disabled">
              <span>{{ $t(subItem.title) }}</span>
            </el-menu-item>
          </el-menu-item-group>
        </el-sub-menu>
        <el-menu-item v-else :index="item.index" :disabled="item.disabled" :title="item.title">
          <el-icon><component :is="item.icon" /></el-icon>
          <span>{{ $t(item.title) }}</span>
        </el-menu-item>
      </template>
    </el-menu>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import eventBus from '@/utils/eventbus';
import { menuItems } from '@/router/menu';
import { Community } from '@/model/Community';
import { config } from '@/config/config';

const router = useRouter();
const activeIndex = ref('2');
const community = ref(JSON.parse(localStorage.getItem('community')));
const collapsed = ref(true);

// 监听 community 变化
const communityChange = (commu: Community) => {
  community.value = commu;
};

onMounted(() => {
  eventBus.on('communityChange', communityChange);
});

onBeforeUnmount(() => {
  eventBus.off('communityChange', communityChange);
});

const handleSelect = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
  router.push(key);
};

// const toggleCollapse = () => {
//   collapsed.value = !collapsed.value;
// };
</script>

<style scoped>

.logo {
  margin: 12px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.name {
  margin-top: -10px;
  margin-bottom: 10px;
  width: 100%;
  font-size: 14px;
  text-align: center;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>